//
//  HMTabBarContentView.m
//  Pods
//
//  Created by WangYong on 2017/9/11.
//
//

#import "HMTabBarContentView.h"
#import <Masonry/Masonry.h>

@interface HMTabBarContentView ()<UIScrollViewDelegate>

@property(strong,nonatomic) UIScrollView * tabBar;

@property(strong,nonatomic) UIScrollView *contentContainer;

@property(strong,nonatomic) NSMutableArray <UIButton *> *itemsButton;

@property(strong,nonatomic) NSMutableArray <UIView *> *contentViews;
//选中的选项按钮
@property(strong,nonatomic) UIButton *selectedItemButton;
//选中的容器视图
@property(strong,nonatomic) UIView *selectedContainerView;

@end

@implementation HMTabBarContentView

#pragma mark - 属性重写
- (NSMutableArray<UIButton *> *)itemsButton
{
    if (_itemsButton == nil) {
        _itemsButton = [NSMutableArray new];
    }
    return _itemsButton;
}

- (NSMutableArray<UIView *> *)contentViews
{
    if (_contentViews == nil) {
        _contentViews = [NSMutableArray array];
    }
    return _contentViews;
}

#pragma mark - 私有方法
- (NSInteger)numberOfItems{
    if (self.datasource && [self.datasource respondsToSelector:@selector(numberOfItemsInTabBarContentView:)]) {
        return [self.datasource numberOfItemsInTabBarContentView:self];
    }
    return 0;
}

#pragma mark - 刷新数据
- (void)reloadData
{
    CGFloat tabBarHeight = 30;

    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBarHeightInTabBarContentView:)]) {
        tabBarHeight = [self.delegate tabBarHeightInTabBarContentView:self];
    }

    if (self.tabBar == nil) {
        self.tabBar = [UIScrollView new];
        self.tabBar.backgroundColor = [UIColor clearColor];
        self.tabBar.showsVerticalScrollIndicator = NO;
        self.tabBar.showsHorizontalScrollIndicator = NO;

        [self addSubview:self.tabBar];
        [self.tabBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self);
            make.height.mas_equalTo(tabBarHeight);
        }];

        //tabBar底部背景线
        UIView *tabBarBottomLine = [UIView new];

        [self.tabBar addSubview:tabBarBottomLine];
        tabBarBottomLine.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
        [tabBarBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.width.equalTo(self.tabBar);
            make.top.equalTo(tabBarBottomLine.mas_bottom).offset(-(1.0/[UIScreen mainScreen].scale));
            make.height.mas_equalTo(1.0/[UIScreen mainScreen].scale);
        }];

        //选中容器视图
        self.selectedContainerView = [UIView new];
        self.selectedContainerView.backgroundColor = [UIColor clearColor];
        self.selectedContainerView.userInteractionEnabled = NO;
        [self.tabBar addSubview:self.selectedContainerView];
        [self.selectedContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.width.height.equalTo(self.tabBar);
        }];
    }else {
        [self.tabBar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self);
            make.height.mas_equalTo(tabBarHeight);
        }];
    }

    if (self.contentContainer == nil) {
        self.contentContainer = [UIScrollView new];

        self.contentContainer.backgroundColor = [UIColor clearColor];
        self.contentContainer.pagingEnabled = YES;
        self.contentContainer.showsVerticalScrollIndicator =NO;
        self.contentContainer.showsHorizontalScrollIndicator = NO;
        self.contentContainer.delegate = self;

        [self addSubview:self.contentContainer];
        [self.contentContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.top.equalTo(self.tabBar.mas_bottom);
        }];
    }else {
        [self.contentContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.top.equalTo(self.tabBar.mas_bottom);
        }];
    }

    //构建tabBar内部按钮
    //获取数量
    NSInteger itemCount = [self numberOfItems];

    float precent = (ceil((1.0/itemCount)*1000))*0.001;

    [self.itemsButton removeAllObjects];

    //循环创建按钮
    for (NSInteger i = 0; i < itemCount; i++) {
        UIButton* itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [itemButton addTarget:self action:@selector(actionSelectItemButton:) forControlEvents:UIControlEventTouchUpInside];
        //设置button标题
        if (self.datasource && [self.datasource respondsToSelector:@selector(tabBarContentView:titleAtItemIndex:)]) {
            NSString *title = [self.datasource tabBarContentView:self titleAtItemIndex:i];

            [itemButton setTitle:title forState:UIControlStateNormal];
        }
        itemButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [itemButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [itemButton setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];

        [self.tabBar addSubview: itemButton];
        [self.itemsButton addObject:itemButton];
    }

    //Block属性
    __block CGFloat restPercent = 1.0;

    //布局按钮
    for (NSInteger i = 0; i < itemCount; i++) {
        UIButton *itemBtn = self.itemsButton[i];

        [itemBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            if (i == 0) {
                make.left.equalTo(self.tabBar);
                if (itemCount > 1) {
                    make.right.equalTo(self.itemsButton[i+1].mas_left);
                }
            }

            if (i == itemCount - 1) {
                make.right.equalTo(self.tabBar.mas_right);
                if (itemCount > 1) {
                    make.left.equalTo(self.itemsButton[i-1].mas_right);
                }
            }

            if (i > 0 && i < itemCount -1) {
                make.left.equalTo(self.itemsButton[i-1].mas_right);
                make.right.equalTo(self.itemsButton[i+1].mas_left);
            }

            make.top.bottom.height.equalTo(self.tabBar);

            if (i != itemCount - 1) {
                make.width.equalTo(self.tabBar.mas_width).multipliedBy(precent);
                restPercent = restPercent - precent;
            } else {
                make.width.equalTo(self.tabBar.mas_width).multipliedBy(restPercent);
            }
        }];

    }

    //清理缓存
    [self.contentViews removeAllObjects];

    //添加内容
    for (NSInteger i = 0; i < itemCount; i++) {
        UIView *contentView = nil;
        if (self.datasource && [self.datasource respondsToSelector:@selector(tabBarContentView:contentViewAtItemIndex:)]) {
            contentView = [self.datasource tabBarContentView:self contentViewAtItemIndex:i];
        } else {
            contentView = [UIView new];
        }

        [self.contentContainer addSubview:contentView];
        [self.contentViews addObject:contentView];
    }

    //布局内容视图
    for (NSInteger i = 0; i < itemCount; i++) {
        UIView *contentView = self.contentViews[i];

        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (i == 0) {
                make.left.equalTo(self.contentContainer);
                if (itemCount > 1) {
                    make.right.equalTo(self.contentViews[i + 1].mas_left);
                }
            }

            if (i == itemCount - 1) {
                make.right.equalTo(self.contentContainer.mas_right);
                if (itemCount > 1) {
                    make.left.equalTo(self.contentViews[i-1].mas_right);
                }
            }

            if (i > 0 && i < itemCount -1) {
                make.left.equalTo(self.contentViews[i-1].mas_right);
                make.right.equalTo(self.contentViews[i+1].mas_left);
            }

            make.top.bottom.width.height.equalTo(self.contentContainer);
        }];
    }


    //把自定义的高亮的选中视图添加到选中容器中
    NSArray *subviews = [self.selectedContainerView subviews];

    //清理缓存
    for (UIView *view in subviews) {
        [view removeFromSuperview];
    }

    if (self.delegate && [self.delegate respondsToSelector:@selector(heightLightTabBarItemViewInTabBarContentView:)]) {
        UIView *heightlightView = [self.delegate heightLightTabBarItemViewInTabBarContentView:self];

        if (heightlightView) {
            [self.selectedContainerView addSubview:heightlightView];
            [heightlightView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.selectedContainerView);
            }];
        }
    }

    //默认选中第一个按钮
    if (self.itemsButton.count > 0) {
        [self selectItemButton:self.itemsButton.firstObject];
    }
}

#pragma mark - 私有方法 - 
- (void)selectItemButton:(UIButton *)button {
    if (self.selectedItemButton != nil && self.selectedItemButton == button) {
        return;
    }

    //将上一个按钮取消选中
    if (self.selectedItemButton != nil) {
        self.selectedItemButton.selected = NO;
        self.selectedItemButton = nil;
    }

    self.selectedItemButton = button;

    [self.selectedContainerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.height.width.equalTo(self.selectedItemButton);
    }];

    //获取被点击时的索引
    NSInteger selectedIndex = [self.itemsButton indexOfObject:button];

    self.selectedItemButton.selected = YES;

    [self.contentContainer setContentOffset:CGPointMake(self.contentContainer.frame.size.width * selectedIndex, self.contentContainer.contentOffset.y) animated:YES];

    //让按钮处于被选中状态
    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBarContentView:didSelectedAtIndex:)]) {
        [self.delegate tabBarContentView:self didSelectedAtIndex:selectedIndex];
    }
}

#pragma mark - action事件 - 
- (void)actionSelectItemButton:(UIButton *)button{
    [self selectItemButton:button];
}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.contentContainer) {
        //处理滚动联动
        //导航条当前位置 = 内容当前位置 / 内容移动最大位置 * 导航条能移动的最大位置
        CGFloat tabBarOffsetX = scrollView.contentOffset.x /( scrollView.contentSize.width - scrollView.frame.size.width) * (self.tabBar.contentSize.width - self.itemsButton.lastObject.frame.size.width);

        self.selectedContainerView.frame = CGRectMake(tabBarOffsetX, self.selectedContainerView.frame.origin.y, self.selectedContainerView.frame.size.width, self.selectedContainerView.frame.size.height);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.contentContainer) {
        NSInteger selectedIndex = scrollView.contentOffset.x / scrollView.frame.size.width;

        //设置选中按钮
        UIButton *selectedBtn = self.itemsButton[selectedIndex];

        [self selectItemButton:selectedBtn];
    }
}




@end
